<script setup>
import MainContainer from '@/components/MainContainer.vue';
import { ref } from 'vue';
import { useAdminStore } from '@/stores';
import { userGetList, userGetListBySearch, usernameCheck, userAdd, userDel, roleGetList, userBatchStatusUpdate, userUpdate, userStatusUpdate } from '@/api/setting';
import { ElMessage } from 'element-plus';

const userList = ref([]);
const deptList = ref([]);
const roleList = ref([])
const jobList = ref([]);
const isEdit = ref(false)
const isConfirm = ref(false)
const delId = ref('')
//新增/编辑用户对话框
const userDialogVisable = ref(false)
//分页相关
const page = ref(1)
const pageSize = ref(10)
const pageTotal = ref('')
const _userDetail = {
  username: "",
  name: "",
  gender: 1,
  code: "",
  phone: "",
  email: "",
  dept: "",
  job: "",
  role: "",
  status: ""
}
const _userSearchList = {
  username: '',
  name: '',
  status: '',
  dept: '',
  job: '',
}
const dialogTitle = () => {
  if (isEdit.value) {
    return '编辑用户'
  } else {
    return '新增用户'
  }
}
// 重置搜索数据为初始值
const userSearchList = ref({ ..._userSearchList })
const resetUserSearchList = () => {
  Object.assign(userSearchList.value, _userSearchList)
}
// 重置用户数据为初始值
const userDetail = ref({ ..._userDetail })
const resetUserDetail = () => {
  Object.assign(userDetail.value, _userDetail)
}

// 获取用户列表(初始化),并缓存
const adminStore = useAdminStore()
adminStore.getDeptCasList()
deptList.value = adminStore.deptList
const getuserList = async () => {
  const resUser = await userGetList({ page: page.value, pageSize: pageSize.value });
  console.log(resUser.data.data)
  userList.value = resUser.data.data.records
  pageTotal.value = resUser.data.data.total
}

const getroleList = async () => {
  const resRole = await roleGetList()
  roleList.value = resRole.data.data
  console.log(roleList.value)
  console.log(deptList.value)
}
getuserList({ page: page.value, pageSize: pageSize.value })
getroleList();
// 处理分页查询
const handleChange = async (currentpage, pageSize) => {
  page.value = currentpage
  pageSize.value = pageSize
  await getuserList({ page: page.value, pageSize: pageSize.value })
}
adminStore.getDeptCasList()
// 选择查询部门，并获取部门对应岗位
const cascaderRef = ref('')
const loadJobList = (value) => {
  console.log(value)
  userDetail.value.dept = value.at(-1)
  const deptResult = ref([])
  deptResult.value = deptList.value
  for (let i = 1; i < value.length; i++) {
    deptResult.value = deptResult.value[0].children.filter((item) => item.id === value[i])
  }
  jobList.value = deptResult.value[0].joblist.map(item => item.name)
  console.log(jobList.value)
}
// 条件查询
const getUserListBySearch = async () => {
  userSearchList.value.dept = userSearchList.value.dept.at(-1)
  console.log(userSearchList.value.dept)
  // console.log(userSearchList.value)
  await userGetListBySearch({ username: userSearchList.value.username, name: userSearchList.value.name, status: userSearchList.value.status, deptId: userSearchList.value.dept, job: userSearchList.value.job, page: page.value, pageSize: pageSize.value })
    .then((res) => {
      userList.value = res.data.data.records
      pageTotal.value = res.data.data.total
    })
  resetUserSearchList()
}
// 搜索重置
const restUserList = async () => {
  resetUserSearchList()
  await getuserList({ page: page.value, pageSize: pageSize.value })
}
// 批量修改状态：获取多选的表格行元素->提交状态修改->刷新用户表格数据
const tableRef = ref(null)
const handleBatch = async (statusTo) => {
  const userInfoList = tableRef.value.getSelectionRows()
  console.log(userInfoList)
  console.log({ userInfoList, statusTo })
  await userBatchStatusUpdate({ userInfoList: userInfoList, statusTo: statusTo })
  await getuserList({ page: page.value, pageSize: pageSize.value })
}
//打开新增用户
const openUserDialog = () => {
  userDialogVisable.value = true
  isEdit.value = false
  resetUserDetail()
  Object.assign(ischecknameShow.value, _ischecknameShow)
}
//新增/修改的用户名验证
const _ischecknameShow = {
  check: false,
  dup: false,
  nodup: false
}
const ischecknameShow = ref({ ..._ischecknameShow })
const checkUsername = async () => {
  Object.assign(ischecknameShow.value, _ischecknameShow)
  console.log(userDetail.value.username)
  if (userDetail.value.username !== '') {
    ischecknameShow.value.check = true
    const res = await usernameCheck(userDetail.value.username)
    console.log(res.data.data)
    if (res.data.data === 0) {
      ischecknameShow.value.check = false
      ischecknameShow.value.nodup = true
    }
    if (res.data.data === 1) {
      ischecknameShow.value.check = false
      ischecknameShow.value.dup = true
    }
  }
}
// 新增/修改用户提交
const submitadduserForm = async () => {
  if (!isEdit.value) {
    // userDetail.value.dept = userDetail.value.dept.at(-1)
    await userAdd(userDetail.value).then((res) => {
      ElMessage.success(res.data.data)
    }).finally(
      userDialogVisable.value = false
    )
  }
  if (isEdit.value) {
    console.log('123:', userDetail.value)
    await userUpdate(userDetail.value)
    userDialogVisable.value = false

    // await userUpdate(userDetail.value)
  }
  await getuserList({ page: page.value, pageSize: pageSize.value })
  resetUserDetail()
}
//修改用户打开界面
const editUser = async (value) => {
  console.log(value)
  isEdit.value = true
  userDialogVisable.value = true
  userDetail.value = value
  console.log(userDetail.value)
  console.log(isEdit.value)
}
//用户删除
const handleDel = (id) => {
  isConfirm.value = true
  delId.value = id
}
const deleteUser = async () => {
  console.log(delId.value)
  await userDel(delId.value).then(res => {
    ElMessage.success(res.data.data)
  })
  isConfirm.value = false
  resetUserDetail()
  await getuserList({ page: page.value, pageSize: pageSize.value })
}
const optionProps = {
  label: 'name',
  value: 'id'
}
async function changeStatus(row) {
  console.log(row.id, row.status)
  await userStatusUpdate(row.id, row.status).then(res => {
    ElMessage.success(res.data.data)
  })
  await getuserList({ page: page.value, pageSize: pageSize.value })
}
</script>

<template>
  <main-container title="用户管理">
    <div class="search-box">
      <el-form class="search" :inliner="true" :model="userSearchList" id="search">
        <el-form-item>
          <el-input v-model="userSearchList.username" style="max-width: 200px;" placeholder="搜索用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="userSearchList.name" style="max-width: 200px;" placeholder="搜索姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-cascader v-model="userSearchList.dept" :options="deptList" :props="optionProps" @change="loadJobList"
            ref="cascaderRef" placeholder=" 部门" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="userSearchList.job" style="max-width: 250px; min-width: 150px;" placeholder="岗位">
            <el-option v-for="item in jobList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="userSearchList.status" style="max-width: 100px; min-width: 150px" placeholder="启用状态">
            <el-option value="1" label="启用"></el-option>
            <el-option value="0" label="停用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserListBySearch">查询</el-button>
          <el-button type="primary" plain @click="restUserList">重置</el-button>
        </el-form-item>
      </el-form>
      <el-divider class="divider" direction="vertical"></el-divider>
      <div class="active-user" v-auth="['admin:user:status']">
        <el-link @click="handleBatch('1')"><el-icon color="green" style="margin-right: 5px">
            <SwitchButton />
          </el-icon>启用账号</el-link>
        <el-link @click="handleBatch('0')"><el-icon color="red" style="margin-right: 5px; margin-left: 20px">
            <SwitchButton />
          </el-icon>停用账号</el-link>
      </div>
      <el-divider class="divider" direction="vertical"></el-divider>
      <el-button v-auth="['admin:user:add']" type="primary" @click="openUserDialog">新建用户</el-button>
    </div>

    <div class="search-table">
      <el-table ref="tableRef" :data="userList" width="100%" fit>
        <el-table-column header-align="center" align="center" type="selection" width="55"></el-table-column>
        <el-table-column header-align="center" align="center" type="index" label="序号" width="80"></el-table-column>
        <el-table-column header-align="center" align="center" label="用户名" prop="username" width="120"></el-table-column>
        <el-table-column header-align="center" align="center" label="姓名" prop="name"></el-table-column>
        <el-table-column header-align="center" align="center" label="工号" prop="code"></el-table-column>
        <el-table-column header-align="center" align="center" label="性别" width="80">
          <template #default="scope">
            <div>{{ scope.row.gender === '1' ? "男" : "女" }}</div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="手机号" prop="phone"></el-table-column>
        <el-table-column header-align="center" align="center" label="邮箱" prop="email"></el-table-column>
        <el-table-column header-align="center" align="center" label="状态" width="80">
          <template #default="{ row }">
            <el-switch inline-prompt active-text="启用" inactive-text="停用" v-model="row.status" active-value="1"
              inactive-value="0" @change="changeStatus(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="部门" prop="dept"></el-table-column>
        <el-table-column header-align="center" align="center" label="岗位" prop="job"></el-table-column>
        <el-table-column header-align="center" align="center" label="角色" prop="role"></el-table-column>
        <el-table-column header-align="center" align="center" label="操作">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
              <el-button v-auth="['admin:user:update']" size="small" @click="editUser(scope.row)" type="primary">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
              <el-button v-auth="['admin:user:del']" @click="handleDel(scope.row.id)" size="small" type="danger">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="未查询到数据" />
        </template>
      </el-table>
      <el-pagination class="pagination" v-model:current-page="page" v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]" small background layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal" @change="handleChange"></el-pagination>
    </div>
    <!-- 删除确认对话框 -->
    <el-dialog v-model="isConfirm" width="400" show-close="false">
      <span>
        <img src="@/assets/error.png" class="delConfirm">
        是否确认删除用户</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isConfirm = false">取消</el-button>
          <el-button type="primary" @click="deleteUser()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增/修改用户对话框 -->
    <el-dialog ref="userDetailFormRef" class="add-dialog" v-model="userDialogVisable" :title="dialogTitle()"
      width="400px">
      <el-form :model="userDetail" class="add-form" label-width="auto">
        <el-form-item label="用户名" required prop="username">
          <el-input v-model="userDetail.username" class="username" :disabled="isEdit"></el-input>
          <div style="margin-top: 5px; margin-left: 10px;" v-if="!isEdit">
            <el-button @click="checkUsername" size="small" type="primary">检查用户名</el-button>
            <span class="dupName" v-if="ischecknameShow.check">
              <img src="@/assets/Loading.png" class="loading loading-active">
              <el-text size="small">查询是否重名</el-text>
            </span>
            <span class="dupName" v-if="ischecknameShow.dup">
              <img src="@/assets/error.png" class="loading">
              <el-text size="small">用户名冲突</el-text>
            </span>
            <span class="dupName" v-if="ischecknameShow.nodup">
              <img src="@/assets/ok.png" class="loading">
              <el-text size="small">用户名可用</el-text>
            </span>
          </div>
        </el-form-item>

        <el-form-item label="姓名" required prop="name">
          <el-input v-model="userDetail.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userDetail.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userDetail.email"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userDetail.gender" aria-label="性别">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="编号" prop="code">
          <el-input v-model="userDetail.code"></el-input>
        </el-form-item>
        <el-form-item label="部门" required prop="dept">
          <el-cascader v-model="userDetail.dept" :options="deptList" :props="optionProps" @change="loadJobList"
            placeholder="部门" />
        </el-form-item>
        <el-form-item label="岗位" required prop="job">
          <el-select v-model="userDetail.job">
            <el-option v-for="item in jobList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" required prop="role">
          <el-select v-model="userDetail.role">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName"
              :value="item.roleName"></el-option>
          </el-select>
        </el-form-item>
        <div class="btn">
          <el-button type="primary" @click="submitadduserForm()">确定</el-button>
          <el-button @click="userDialogVisable = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </main-container>

</template>

<style scoped lang="less">
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  align-items: center;
  padding: 20px 50px;
  border-bottom: 1px solid #E4E7ED;
  background-color: var(--el-color-primary-light-8);

  // .divider {
  //   height: 2em;
  // }

  .search {
    display: flex;
    width: 70%;
    justify-content: space-between;
    align-items: center;

    .el-form-item {
      margin-bottom: 0px;
    }

    .el-select {
      margin-right: 10px;
    }
  }

  .active-user {
    margin-right: 10px;
  }
}

.search-table {
  padding: 10px 50px;
}

.add-dialog {
  padding: 20px 20px;

  .add-form {
    // display: flex;
    // flex-direction: column;
    padding: 10px 20px;

    .btn {
      display: flex;
      justify-content: center;
    }
  }
}

.pagination {
  display: flex;
  justify-content: end;
  margin-top: 20px;
  margin-right: 50px;
}

.dupName {
  margin-top: 10px;
  line-height: 100%
}

.loading {
  vertical-align: middle;
  margin-right: 10px;
  width: 1em;
  height: 1em;
  margin-left: 10px;

}

.loading-active {
  animation: loader 1s infinite linear;
}

:deep(.el-form-item .el-form-item__label) {
  height: 80px;
  line-height: 80px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

@keyframes loader {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.username {
  flex-direction: column;
}

.delConfirm {
  height: 2rem;
  vertical-align: middle;
}
</style>
